//  node  文件上传
const fs = require('fs')
exports.uploadFile = function (req, res, next) {
  var fileName = req.file.filename;
  var destDir = req.body.dir == undefined ? "default" : req.body.dir;
  var sourceFile = req.file.path;
  var destPath = path.join(__dirname.replace("routes", ""), "uploads", destDir, fileName);
  var dest_Dir = path.join(__dirname.replace("routes", ""), "uploads", destDir);
  var fileurl = uploadFileDomin + destPath.substr(destPath.indexOf("uploads"));
  fileurl = fileurl.replace(/\\/g, "/");
  fs.exists(dest_Dir, function (exists) {
      if (exists) {
          fs.rename(sourceFile, destPath, function (err) {
              res.status(200).json({
                  httpCode: 200,
                  message: '上传成功',
                  data: {
                      "fileurl": fileurl
                  },
              });
          });
      }
      else {
          fs.mkdir(dest_Dir, 0777, function (err) {
              if (err) {
                  res.status(500).json({
                      httpCode: 500,
                      message: err,
                      data: [],
                  });
              } else {
                  fs.rename(sourceFile, destPath, function (err) {
                      res.status(200).json({
                          httpCode: 200,
                          message: '上传成功',
                          data: {
                              "fileurl": fileurl
                          },
                      });
                  });
              }
          })
      }
  });

}

